// ================================ 搜索热词 ================================
(function($) {

    let listIndex = -1; // 当前高亮项的索引
    let parent = null; // 当前搜索框的父容器
    let tipsList = 0; // 联想词总数
    let currentSuggestions = []; // 缓存联想词数据
    let isSiteInternal = false; // 默认关闭站内搜索

    const $searchBox = $('#search-text');
    const $tips = $('.search-smart-tips');
    const $word = $('#word');
    const $ul = $tips.find('ul');

    $('#internal-search-checkbox').on('change',function() {
        isSiteInternal = $(this).is(':checked');
        const $searchText = $('#search-text');
        const $searchPlaceholder = $searchText.attr('placeholder');
        const internalSearchPlaceholder = '🏠 🔍 想找什么资源？试试输入「Github」「Web」... ';
        if ($searchPlaceholder && $searchPlaceholder !== internalSearchPlaceholder) {
            // 保存原始 placeholder
            $searchText.data('original-placeholder', $searchPlaceholder);
        }
        // 关闭联想框
        hiddenSuggestions();
        if (isSiteInternal) {
            // 保留布局并快速隐藏
            $('#search-list-menu')
                .css('transition', 'none')  // 禁用过渡
                .css('opacity', '0')
                .css('pointer-events', 'none');
            $('#search-list')
                .css('transition', 'none')
                .css('opacity', '0')
                .css('pointer-events', 'none');
            // 隐藏搜索框提示词
            $searchText.attr('placeholder', internalSearchPlaceholder);
        } else {
            $('#search-list-menu')
                .css('opacity', '1')
                .css('pointer-events', 'auto');
            $('#search-list')
                .css('opacity', '1')
                .css('pointer-events', 'auto');
            // 恢复搜索框提示词
            $searchText.attr('placeholder', $searchText.data('original-placeholder'));
        }
        // console.debug('[module] 切换为:', isSiteInternal ? '站内搜索' : '全网搜索');
    });

    /*
     * 获取网站菜单数据
     * @returns {Array} 菜单数据数组
     */
    function getMenuData() {
        const menuData = [];
        $('#sidebar .sidebar-menu-inner > ul > li').each(function () {
            const $li = $(this);
            const $catalog = $li.find('> a');
            const $items = $li.find('ul li a');

            const catalogItem = {
                catalog: $catalog.find('span').text().trim(),
                href: $catalog.attr('href'),
                items: []
            };

            $items.each(function () {
                const $item = $(this);
                catalogItem.items.push({
                    name: $item.find('span').text().trim(),
                    href: $item.attr('href')
                });
            });

            menuData.push(catalogItem);
        })
        return menuData;
    }

    /*
     * 获取网站收集的网站数据
     * @returns {Array} 网站数据数组
     */
    function getWebData() {
        const webData = [];
        const urlSet = new Set(); // 用于检测重复URL

        $('#content .url-body > a.card').each(function () {
            const $link = $(this);
            const url = $link.attr('href')?.trim(); // 使用可选链操作符
            // 检查 URL 是否有效且不重复
            if (url && window.AppUtils.isValidUrl(url) && !urlSet.has(url)) {
                urlSet.add(url); // 记录已处理的URL
                webData.push({
                    name: $link.data('name'),
                    description: $link.data('description'),
                    url: $link.attr('href'),
                    icon: $link.find('img').attr('src')
                });
            }
        })
        return webData;
    }

    /*
     * 高亮关键字
     * @param {string} text - 文本内容
     * @param {string} keyword - 关键字
     * @returns {string} 高亮后的文本
     */
    function highlightKeyword(text, keyword) {
        const regex = new RegExp(keyword, 'gi');
        return (text || '').replace(regex, '<mark>$&</mark>');
    }

    /*
     * 预处理内容，去掉首尾空格和特殊字符
     * @param {string} content - 文本内容
     * @returns {string} 预处理后的文本
     */
    function preCleanContent(content) {
        return content.trim().replace(/[\s\-_+.]/g, '').toLowerCase()
    }

    // 静态数据，直接初始化即可
    const webData = getWebData();
    const menuData = getMenuData();
    /*
     * 通过匹配关键字获取网站数据
     * @param {string} keyword - 搜索关键字
     */
    function getSiteData(keyword) {
        // 去掉首尾、中间的空格
        keyword = preCleanContent(keyword);
        let isMatch = false; // 是否匹配到结果

        if (!keyword) {
            initSuggestions();
            return;
        }

        $word.empty().show();

        // 创建文档片段
        const $fragment = $(document.createDocumentFragment());

        // 匹配菜单数据
        const matchedMenus = [];

        if (!$('#simple-mode').data('simple')) {
            // 先检查二级菜单匹配
            menuData.forEach(menu => {
                const menuInfo = preCleanContent(menu.catalog);
                if (menuInfo.includes(keyword)) {
                    // 如果匹配到一级菜单，添加完整的一级菜单
                    matchedMenus.push({
                        ...menu
                    });
                }
                else {
                    const matchedSubmenus = menu.items.filter(sub =>
                        preCleanContent(sub.name).includes(keyword)
                    );
                    if (matchedSubmenus.length > 0) {
                        // 如果匹配到二级菜单，添加完整的一级菜单和匹配的二级菜单
                        matchedMenus.push({
                            ...menu,
                            items: matchedSubmenus, // 只保留匹配的二级菜单
                        });
                    }
                }
            });
            if (matchedMenus.length > 0) {
                // 渲染匹配的菜单结果
                matchedMenus.forEach(menu => {
                    isMatch = true;
                    $fragment.append(`
                    <div class="card-body">
                        <div class="menu-header" data-href="${menu.href}">
                            <a class="search-catalog" href="${menu.href}">
                                <i class="fas fa-folder-open"></i>
                                <strong>${highlightKeyword(menu.catalog, keyword)}</strong>
                            </a>
                        </div>
                        <div class="submenu-list">
                            ${menu.items.map(sub => `
                                <a class="search-catalog-item" href="${menu.href}">
                                    <div class="submenu-item" data-href="${sub.href}">
                                        <i class="fas fa-file-alt"></i>
                                        <span>${highlightKeyword(sub.name, keyword)}</span>
                                    </div>
                                </a>
                            `).join('')}
                        </div>
                    </div>
                `);
                });
            }
        }

        // 是否已经添加过分隔线
        let addedHr = false;
        // 匹配网站数据
        webData.filter(item =>
            preCleanContent(item.name).includes(keyword) ||
            preCleanContent(item.description || '').includes(keyword)
        ).forEach(item => {
            isMatch = true;
            // 在添加新卡片前检查并插入分隔线
            if (!addedHr && $fragment.children().length > 0) {
                $fragment.append('<hr class="card-divider">'); // 添加分隔线
                addedHr = true;
            }
            $fragment.append(`
                <a class="search-web"  href="${item.url}" target="_blank" rel="noopener noreferrer">
                    <div class="card-body">
                        <div class="url-content d-flex align-items-center">
                            <div class="url-img mr-2 d-flex align-items-center justify-content-center">
                                <img class="lazy" src="${item.icon}" width="20" height="20" alt="网站图标">
                            </div>
                            <div class="url-info flex-fill">
                                <div class="text-sm overflowClip_1">
                                    <strong>${highlightKeyword(item.name, keyword)}</strong>
                                </div>
                                <p class="overflowClip_1 m-0 text-muted text-xs search-web-desc">${highlightKeyword(item.description, keyword)}</p>
                            </div>
                        </div>
                    </div>
                </a>
            `);
        })

        if (isMatch === true) {
            // 检查元素是否存在
            if ($word.length) {
                // 获取视口高度(100vh对应的像素值)
                const viewportHeight = window.innerHeight;
                // 计算最大可用高度
                const maxHeight = viewportHeight - window.AppUtils.getOffsetTopFromBody($word) - 200;
                // 设置高度（确保不小于0）且元素存在
                $word.css('max-height', `${Math.max(200, maxHeight)  }px`);
            }
            $tips.length > 0 && $tips.slideDown(200);
        } else {
            initSuggestions();
            $fragment.append(`
            <div class="card">
                <div class="card-body text-center py-5">
                    <div class="empty-state">
                        <div class="empty-state-icon bg-light rounded-circle">
                            <i class="bi bi-search text-muted fs-1"></i>
                        </div>
                        <i class="iconfont icon-crying" style="font-size: 30px; margin-bottom: 30px;"></i>
                        <p class="text-muted mb-4 empty-search-result">抱歉，没找到与您的搜索匹配的内容</p>
                    </div>
                </div>
            </div>
            `)
        }
        // 一次性插入所有结果
        $ul.empty().append($fragment);
    }

    /*
     * 清洗热词
     * @returns {string} 清洗后的文本（移除序号等标记）
     */
    function cleanHotValue(html_content) {
        return (html_content || "").replace(/^<span>\d+<\/span>/, "")
    }


    /*
     * 专用渲染函数（保证DOM与数据一致）
     */
    function renderSuggestions(items) {
        // 清空现有建议列表
        $ul.empty();
        items.forEach((item, index) => {
            $ul.append(`<li data-index="${index}">${item}</li>`);
        });
        tipsList = items.length;
    }

    /*
     * 通用搜索提示函数
     * @param {string} engine - 搜索引擎类型（'baidu'/'google'）
     * @param {string} keyword - 搜索关键词
     * @param {jQuery} $parent - 父容器元素
     */
    function getSmartTips(engine, keyword, $parent) {
        const $tips = $parent.find(".search-smart-tips");

        // API配置
        const apis = {
            baidu: {
                type: "GET",
                url: "//sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su",
                async: true,
                params: {wd: keyword, cb: 'iowenHot'},
                jsonp: "cb",
                dataField: "s" // 百度返回数据字段
            },
            google: {
                type: "GET",
                url: "//suggestqueries.google.com/complete/search",
                async: true,
                params: {q: keyword, client: "firefox", callback: 'iowenHot'},
                jsonp: "callback",
                dataField: "1" // 谷歌返回数据字段
            }
        };

        if (!apis[engine]) return;

        $.ajax({
            type: apis[engine].type,
            url: apis[engine].url,
            async: apis[engine].async,
            data: apis[engine].params,
            dataType: "jsonp",
            jsonp: apis[engine].jsonp,
            success (res) {
                const data = res[apis[engine].dataField] || [];
                currentSuggestions = data.slice(); // 创建新数组避免引用问题
                listIndex = -1; // 重置索引
                $word.empty().show();
                if (currentSuggestions.length > 0) {
                    renderSuggestions(currentSuggestions); // 专用渲染函数
                    // 有建议项时，显示建议列表
                    $tips.slideDown(200);
                    visibleSuggestions();
                } else {
                    // 如果没有建议项，隐藏建议列表
                    $tips.slideUp(200);
                    hiddenSuggestions();
                }
            },
            error () {
                // 异常时隐藏建议列表
                $tips.slideUp(200);
                tipsList = 0;
                listIndex = -1
                hiddenSuggestions();
            }
        });
    }

    /*
     * 更新高亮项（基于缓存数据）
     * @param {number} newIndex - 新的索引位置
     */
    function updateHighlight(newIndex) {
        const $items = parent.find(".search-smart-tips ul li");

        if (!currentSuggestions.length) return;

        // 循环索引
        listIndex = (newIndex + currentSuggestions.length) % currentSuggestions.length;
        // 更新高亮
        $items.removeClass("current");
        $items.eq(listIndex).addClass("current");
        // 更新输入框
        $searchBox.val(currentSuggestions[listIndex]).trigger('change');
    }

    /*
     * 清空并显示联想词
     */
    function initSuggestions() {
        $tips.css('opacity', '0')
        $tips.css('display', '')
    }

    /*
     * 隐藏联想词
     */
    function hiddenSuggestions() {
        $word.empty().hide();
    }

    /*
     * 隐藏联想词
     */
    function visibleSuggestions() {
        if ($word.children().length > 0) {
            $tips.css('opacity', '1');
        }
    }

    /*
     * 提交搜索表单
     */
    function submitSearchForm(content, shouldRedirect = true) {
        const url = $(".super-search-fm").attr('action')
        const searchUrl = url + encodeURIComponent(content)
        $.ajax({
            url,
            method: "POST",
            data: {search: content},
            complete () {
                $searchBox.val('').trigger('change').trigger('focus');
                hiddenSuggestions();
                if (shouldRedirect) {
                    const newWindow = window.open('', '_blank');
                    // 首选方案：新标签页跳转
                    if (newWindow) {
                        newWindow.location.href = searchUrl;
                    }
                    else {
                        // 降级方案：当前页跳转
                        window.location.href = searchUrl;
                    }
                }
            }
        });
    }

    $('')

    // 点击联想词时触发
    $ul.on('click', 'li', function (e) {
        let selectedText = "";
        // 阻止默认行为，防止表单提交
        e.preventDefault();
        e.stopPropagation();
        if (!isSiteInternal) {
             // 清洗输入框内容
            selectedText = $(this).text().trim();
        }
        // 更新输入框值
        $searchBox.val(selectedText).trigger('change');
        // 关闭提示区域
        $tips.length > 0 && $tips.slideUp(200);
        // 开始提交表单
        submitSearchForm(selectedText);
    });

    // 点击站内搜索结果时触发
    $word.on('click', '.search-catalog, .search-catalog-item, .search-web', () => {
        $searchBox.val('').trigger('change');
        $tips.length > 0 && $tips.stop(true, true).slideUp(200);
    });
    
    // 输入框失去焦点时触发
    $(document).on("blur", ".smart-tips.search-key", () => {
        parent = '';
        $tips.delay(150).slideUp(200)
    });

    // 输入框获得焦点时触发
    $(document).on("focus", ".smart-tips.search-key", window.AppUtils.debounce(function () {
        parent = $(this).closest("#search");
        const keyword = $(this).val().trim();
        if (keyword && !isSiteInternal) {
            switch (window.theme.hotWords) {
                case "baidu":
                    getSmartTips('baidu', keyword, parent);
                    break;
                case "google":
                    getSmartTips('google', keyword, parent);
                    break;
                default:
            }
        }
    }, 200));

    // 输入框内容变化时触发
    $(document).on("keyup", ".smart-tips.search-key", window.AppUtils.debounce(function (e) {
        initSuggestions();

        const inputContent = $(this).val();
        const smartTipsVisible = $(".search-smart-tips #word").css('display') !== "none"
        parent = $(this).parents('#search');

        if (inputContent && inputContent.length > 0) {
            visibleSuggestions();
            if (smartTipsVisible && (e.key === "ArrowDown" || e.key === "ArrowUp")) {
                return
            }
            if (isSiteInternal === true) {
                getSiteData(inputContent);
            }
            else {
                switch (window.theme.hotWords) {
                    case "baidu":
                        getSmartTips('baidu', inputContent, parent);
                        break;
                    case "google":
                        getSmartTips('google', inputContent, parent);
                        break;
                    default:
                }
            }
            listIndex = -1;
        } else {
            // 若输入框为空，通过 slideUp 隐藏提示区域
            $tips.length > 0 && $tips.is(':visible') && $tips.slideUp(200)
        }
    }, 200));

    // 键盘事件处理
    $(document).on("keydown", ".smart-tips.search-key", function (e) {
        const inputContent = $(".smart-tips.search-key").val()
        if (inputContent && inputContent.length > 0) {
            visibleSuggestions();
        }

        parent = $(this).parents('#search');
        const smartTipsVisible = $(".search-smart-tips #word").css('display') !== "none"
        if (!smartTipsVisible) return;

        // 紧急同步检查
        if (currentSuggestions.length !== $ul.find('li').length) {
            // console.debug('[module] 数据不一致，重新渲染');
            renderSuggestions(currentSuggestions);
        }

        // 阻止默认行为，防止页面滚动
        if (e.key === "ArrowDown" || e.key === "ArrowUp" || e.key === "Enter" || e.key === "Delete") {
            e.preventDefault();
        }

        // 选择下一项
        if (e.key === "ArrowDown") {
            updateHighlight(listIndex + 1);
        }
        // 选择上一项
        else if (e.key === "ArrowUp") {
            updateHighlight(listIndex - 1);
        }
        else if (e.key === "Enter") {
            // 回车键选择当前高亮项
            if (listIndex >= 0 && listIndex < tipsList) {
                const $items = parent.find(".search-smart-tips ul li");
                const selectedText = cleanHotValue($items.eq(listIndex).html());
                $searchBox.val(selectedText).trigger('change');
                $tips.length > 0 && $tips.slideUp(200);
                // 浏览器默认会触发提交表单，所以这里 false
                submitSearchForm(selectedText, false);
            }
        }
        else if (e.key === "Delete") {
            $searchBox.val("").trigger('change');
            $tips.length > 0 && $tips.slideUp(200);
            initSuggestions();
        }
    })

    // ================================ 调整搜索框 ================================
    // 获取搜索框元素
    const $searchForm = $('.super-search-fm');
    const $searchSizeRange= $('#searchSizeRange')
    const $searchSizeValue= $('#searchSizeValue')
    const $searchRadiusRange= $('#searchRadiusRange')
    const $searchRadiusValue= $('#searchRadiusValue')

    // 初始化滑块功能
    $searchSizeRange.on('input', function() {
        const size = $(this).val();
        $searchSizeValue.text(`${size  }%`);

        // 调整搜索框宽度
        $searchBox.css('max-width', `${size  }%`);
        $searchForm.css('max-width', `${Number(size) + 30  }%`);
    });
    
    $searchRadiusRange.on('input', function() {
        const radius = $(this).val();
        $searchRadiusValue.text(`${radius  }%`);

        // 计算实际像素值（基于20px基准）
        const pxRadius = (radius / 100) * 20;
        $searchBox.css('border-radius', `${pxRadius  }px`);
    });
    
    // 初始化默认值
    $searchSizeRange.trigger('input');
    $searchRadiusRange.trigger('input');
    
    function loadSettings() {
        const settings = JSON.parse(localStorage.getItem('searchSettings')) || {};
        if (settings.size) {
            $searchSizeRange.val(settings.size).trigger('input');
        }
        if (settings.radius) {
            $searchRadiusRange.val(settings.radius).trigger('input');
        }
    }
    
    function saveSettings() {
        const settings = {
                size: $searchSizeRange.val(),
                radius: $searchRadiusRange.val()
            };
                localStorage.setItem('searchSettings', JSON.stringify(settings));
            }
        
        // 修改事件监听
        $('#searchSizeRange, #searchRadiusRange').on('input', () => {
        saveSettings();
    });

    // 页面加载时读取设置
    loadSettings();
})(window.jQuery);